<?php
declare(strict_types=1);

namespace app\common\model\delivery;

use app\common\model\base\BaseModel;

class MonthBill Extends BaseModel
{

    public function customer()
    {
        return $this->hasOne(Customer::class,'id','customer_id');
    }

    public function goods()
    {
        return $this->hasOne(Goods::class,'id','goods_id');
    }

    public static function createLastBill($customer_id,$goods_id)
    {
        $month=date('Y-m',strtotime('-1 month'));
        $bill=MonthBill::where(['customer_id'=>$customer_id,'goods_id'=>$goods_id,'month'=>$month])->find();
        if($bill){
            return;
        }
        $customer=Customer::find($customer_id);
        $lastmonth=self::getLastMonthOrderDate($customer);
        $last_month_yuefu=ChannelOrder::where(['customer_id'=>$customer_id,'goods_id'=>$goods_id,'is_cancel'=>0,'pay_type'=>'month'])->where('createtime','between',$lastmonth)->field('sum(total_money) as total_money,count(1) as count')->find();
        if(!$last_month_yuefu['total_money']){
            return;
        }
        $data=[
            'month'=>$month,
            'starttime'=>date('Y-m-d H:i:s',$lastmonth[0]),
            'endtime'=>date('Y-m-d H:i:s',$lastmonth[1]),
            'customer_id'=>$customer_id,
            'goods_id'=>$goods_id,
            'total_money'=>$last_month_yuefu['total_money'],
            'count'=>$last_month_yuefu['count'],
            'is_pay'=>0
        ];
        MonthBill::create($data);
    }

    public static function getLastMonthOrderDate($customer)
    {
        $month=date('Y-m',strtotime('-1 month'));
        return self::getMonthOrderDate($customer,$month);
    }

    public static function getThisMonthOrderDate($customer)
    {
        $month=date('Y-m');
        return self::getMonthOrderDate($customer,$month);
    }

    /**
     * 获取指定月份的账单日期的开始时间与结束时间戳
     * @param $customer
     * @param $month
     * @return array
     */
    public static function getMonthOrderDate($customer,$month)
    {
        $bill_date=$customer->bill_date;
        if($bill_date<10){
            $month=$month.'-0'.$bill_date;
        }else{
            $month=$month.'-'.$bill_date;
        }
        $bill_date=strtotime($month);
        $start_time=strtotime('-1 month',$bill_date);
        $end_time=$bill_date-1;
        return [$start_time,$end_time];
    }
}
